package cn.plushine.controller;

import cn.plushine.pojo.POrder;
import cn.plushine.pojo.POrderItem;
import cn.plushine.pojo.SOrder;
import cn.plushine.pojo.SOrderItem;
import cn.plushine.service.BaseInputService;
import cn.plushine.service.BaseOutputService;
import cn.plushine.utils.ResMapUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 出库
 */
@Api(tags = "出库订单")
@Controller
@RestController
@RequestMapping("/admin/product/output")
public class BaseOutputController {

    @Autowired
    BaseOutputService baseOutputService;

    // 获取出库订单
    @ApiOperation(value = "获取出库订单")
    @GetMapping("/get")
    public HashMap<String, Object> get() {
        try {
            // 获取出库订单
            List<SOrder> sOrdersDB = baseOutputService.get();

            // 货物总数（sum），状态判断（flag）
            int sum, flags;
            for (SOrder sOrder : sOrdersDB) {
                sum = sOrder.getSOrders().size();
                flags = 0;
                for (SOrderItem order : sOrder.getSOrders()) {
                    flags += order.getFlags();
                }
                sOrder.setSum(sum);
                // 订单状态判断
                sOrder.setFlags(flags == 0 ? 0 : (flags == sum ? 2 : 1));
            }
            // 成功响应
            return ResMapUtils.encapsulation(200, "获取出库订单成功！", sOrdersDB);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "获取出库订单失败！", e.getMessage());
        }
    }

    // 批量出库
    @ApiOperation(value = "批量出库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "outputId", value = "销售id", paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "keeper", value = "出库人id", paramType = "path", dataType = "int", example = "1"),
            @ApiImplicitParam(name = "multiplySelect", value = "待出库的货物信息", paramType = "body", dataType = "ArrayList<HashMap>")
    })
    @PutMapping("/add/{outputId}/{keeper}")
    public HashMap<String, Object> update(@PathVariable String outputId, @PathVariable int keeper, @RequestBody ArrayList<HashMap> multiplySelect) {
        try {
            // 批量出库
            baseOutputService.update(multiplySelect);
            // 出库时间和出库人信息
            baseOutputService.modify(outputId, keeper);
            // 成功响应
            return ResMapUtils.encapsulation(200, "批量出库成功！", null);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "批量出库失败！", e.getMessage());
        }
    }
}
